﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Vega.USiteBuilder;
using System.Security.Cryptography;
using System.Text;
using SPCFMedicineInformer.Helpers;
using SPCFMedicineInformer.Members;
using System.Web.Security;

namespace SPCFMedicineInformer.UserControls
{
    public partial class LoginControl : Vega.USiteBuilder.WebUserControlBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.Count == 1 && "signout".Equals(Request.QueryString[0], StringComparison.OrdinalIgnoreCase)) //if (Request.QueryString["signout"] != null)
            {
                FormsAuthentication.SignOut();
                Response.Redirect("~/");
            }
        }

        protected void MemberLogin_Authenticate(object sender, AuthenticateEventArgs e)
        {
            string hashedPassword = MemberLogin.Password.ToEncryptedPassword();
            
            var customer = MemberHelper.GetMemberFromLoginAndEncodedPassword(MemberLogin.UserName, hashedPassword) as WebUser;

            bool result = customer != null && customer.Id > 0;
            
            if (result && customer.IsInactive)
            {
                
                MsgLiteral.Text = string.Format("<p class=\"{0}\">{1}</p>", "msg error", "Sorry you cannot login right now, your account was deactivated. Please contact us if you want gain access to your account. Thank you!");
            }
            else if (result)
            {
                
                MemberHelper.LoginWithFormsAuthentication(MemberLogin.UserName,
                    MemberLogin.Password,
                    MemberLogin.RememberMeSet, 30, false);
                if (Request.QueryString["ReturnUrl"] == null)
                {
                    Response.Redirect("/home/");
                }
            }
            else
            {
                MsgLiteral.Text = string.Format("<p class=\"{0}\">{1}</p>", "msg error", "Invalid username or password");
            }
                
        }
    }
}
